package com.bupt.clusterlistener.config;


import cn.hutool.core.collection.CollectionUtil;
import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.util.ClientBuilder;
import io.kubernetes.client.util.KubeConfig;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author soonmachine
 */
@Component
@Slf4j
@Getter
public class ApiClientLoader {

    private Map<String, ApiClient> apiClientMap;

    @PostConstruct
    public void init(){
        apiClientMap = new HashMap<>();
        try {
            apiClientMap.put(KubeConfigPath.NODE1.path,getApiClient(KubeConfigPath.NODE1.path));
            apiClientMap.put(KubeConfigPath.NODE2.path,getApiClient(KubeConfigPath.NODE2.path));
            apiClientMap.put(KubeConfigPath.CLOUD.path,getApiClient(KubeConfigPath.CLOUD.path));
        }catch (IOException e){
            log.error("load api client error:{}",e.getMessage());
        }
    }

    private  ApiClient getApiClient(String filePath) throws IOException {
        String kubeConfigPath = Objects.requireNonNull(this.getClass().getResource("/")).getPath() + filePath;
        return ClientBuilder
                .kubeconfig(KubeConfig.loadKubeConfig(new FileReader(kubeConfigPath)))
                .setVerifyingSsl(false)
                .build();
    }

    public ApiClient getApiClientByPath(KubeConfigPath path){
        if (CollectionUtil.isEmpty(apiClientMap)){
            init();
        }
        return apiClientMap.get(path.path);
    }


    public enum KubeConfigPath {
        /**
         * master1
         */
        NODE1("kubeconfig1"),
        /**
         * master2
         */
        NODE2("kubeconfig2"),
        /**
         * CLOUD
         */
        CLOUD("cloudconfig");

        private final String path;

        KubeConfigPath(String path) {
            this.path = path;
        }
    }

}
